package bootstrap

import (
	"cloud-navigation/global"
	"fmt"
	"os"
	"path/filepath"
	"runtime"

	"github.com/fsnotify/fsnotify"
	"github.com/spf13/viper"
)

// 初始化配置
func InitializeConfig() *viper.Viper {
	config := "config.yaml"

	path := GetAppPath()

	if configEnv := os.Getenv("VIPER_CONFIG"); configEnv != "" {
		config = configEnv
	}

	v := viper.New()
	v.SetConfigFile(filepath.Join(path, config))
	v.SetConfigType("yaml")
	if err := v.ReadInConfig(); err != nil {
		panic(fmt.Errorf("读取配置文件失败: %s", err))
	}
	v.WatchConfig()
	v.OnConfigChange(func(in fsnotify.Event) {
		fmt.Println("配置文件已更新,", in.Name)
		if err := v.Unmarshal(&global.App.Config); err != nil {
			fmt.Println(err)
		}
	})
	if err := v.Unmarshal(&global.App.Config); err != nil {
		fmt.Println(err)
	}

	return v
}

func GetAppPath() string {
	var (
		absPath string
	)

	if global.App.Config.App.Env == "production" {
		exe, err := os.Executable()
		if err != nil {
			panic(err)
		}
		absPath, err = filepath.Abs(exe)
		if err != nil {
			panic(err)
		}
	} else {
		_, filename, _, _ := runtime.Caller(0)
		absPath = filepath.Dir(filename)
	}

	return filepath.Dir(absPath)
}
